<template>
  <!-- w-[80%] max-w-[1600px] mx-auto -->
  <div class="question-page-root">
    <div class="main-layout">
      <div class="main-left ml-6">
        <QuestionMain :tabs="tabs" v-model:activeTab="activeTab" :questions="questionList" :loading="loading" />
        <!-- 分页 -->
        <div class="pagination-container" v-if="total > 0">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
            :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @current-change="handlePageChange"
            @size-change="handleSizeChange" background />
        </div>
      </div>
      <div class="main-right mr-6">
        <!-- <el-button type="primary" class="mb-4 w-full" @click="openDialog()">我要提问</el-button> -->
        <!-- <QuestionFilterBar v-model:sortType="sortType" v-model:onlyUnsolved="onlyUnsolved" v-model:keyword="keyword"
          @filter-change="handleFilterChange" /> -->
        <QuestionCategory :categories="categoryList" :active="activeCategory" @update:active="handleCategoryChange" />
      </div>
    </div>
    <!-- <QuestionDialog v-model:visible="showQuestionDialog" @success="handleQuestionSuccess" /> -->
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { mockQuestions } from './mockQuestions'
import QuestionMain from './QuestionMain.vue'
import QuestionCategory from './QuestionCategory.vue'
// import QuestionFilterBar from './QuestionFilterBar.vue'
import QuestionDialog from '@/views/Submit/components/QuestionDialog.vue'
import { geQuestiontList, getQuestionHotTag } from '@/axios/api/question'
import { getUserInfo } from '@/utils/webStorage'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useGlobalStore } from '@/stores/globalStore'
const globalStore = useGlobalStore()
//头部按钮点击
// watch(
//   () => globalStore.isShowQuestionDialog,
//   (val) => {
//     console.log('val================')
//     console.log(val)
//     if (val) {
//       openDialog()
//     }
//   }
// )

// watch(
//   () => globalStore.heaserClickInfo,
//   (val) => {
//     if (val == '提问') {
//       openDialog()
//     }
//   },
//   { deep: true },
// )

const props = defineProps({
  refreshData: {
    type: Boolean,
    default: false,
  },
})


const route = useRoute()

// 页面状态
const activeTab = ref('')
const loading = ref(false)
const questionList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 恢复页面状态
const restorePageState = async () => {
  if (route.query.from === 'detail') {
    const savedState = sessionStorage.getItem('questionListState')
    if (savedState) {
      const state = JSON.parse(savedState)
      // 如果保存的状态超过30分钟，则不恢复
      if (Date.now() - state.timestamp < 30 * 60 * 1000) {
        activeTab.value = state.activeTab
        // 等待DOM更新后再恢复滚动位置
        await nextTick()
        window.scrollTo(0, state.scrollPosition)
      }
    }
  }
}

// 在组件激活时恢复状态
const activated = async () => {
  await restorePageState()
}


let tabs = []
const curInfo = getUserInfo()
console.log(curInfo);
console.log(JSON.stringify(curInfo) == '{}');

if (JSON.stringify(curInfo) == '{}') {
  tabs = [
    { name: '最新问题', id: 'create_time' },
    { name: '人气问题', id: 'heat_score' },
    { name: '经典答疑', id: 'answer' },
    { name: '专家', id: 'expert' },
  ]
  activeTab.value = 'create_time'
} else if (curInfo.type == 1) {
  tabs = [
    { name: '为您推荐', id: 'recommend' },
    { name: '请您回答', id: 'invite' },
    { name: '最新问题', id: 'create_time' },
    { name: '人气问题', id: 'heat_score' },
    { name: '经典答疑', id: 'answer' },
    { name: '我的提问', id: 'my' },
    { name: '专家', id: 'expert' },
  ]
  activeTab.value = 'recommend'

} else if (curInfo.type == 0) {
  tabs = [
    { name: '为您推荐', id: 'recommend' },
    { name: '最新问题', id: 'create_time' },
    { name: '人气问题', id: 'heat_score' },
    { name: '经典答疑', id: 'answer' },
    { name: '我的提问', id: 'my' },
    { name: '专家', id: 'expert' },
  ]
  activeTab.value = 'recommend'

}





// 筛选项
const sortType = ref('time')
const onlyUnsolved = ref(false)
const keyword = ref('')
const showQuestionDialog = ref(false)
const activeCategory = ref('')

// 分类数据
const categoryList = ref([])
const loadCategories = async () => {
  try {
    const res = await getQuestionHotTag()
    if (res.code === 0 && res.data) {
      categoryList.value = res.data.map(item => ({
        name: item.tagName,
        count: item.questionCount,
        id: item.tagId,
        hot: true // 由于这是热门标签接口，所有标签都是热门的
      }))
    } else {
      // API调用失败，使用mock分类数据
      throw new Error('API调用失败')
    }
  } catch (error) {
    // console.log('获取分类数据失败，使用mock数据：', error)
    // 使用mock分类数据
    // categoryList.value = [
    //   { name: '飞行安全', count: 156, id: '1', hot: true },
    //   { name: '航空法规', count: 89, id: '2', hot: true },
    //   { name: '健康管理', count: 67, id: '3', hot: true },
    //   { name: '职业发展', count: 45, id: '4', hot: true },
    //   { name: '航空新闻', count: 123, id: '5', hot: true },
    //   { name: '心理健康', count: 78, id: '6', hot: true },
    //   { name: '飞行技术', count: 234, id: '7', hot: true },
    //   { name: '其他', count: 34, id: '8', hot: true }
    // ]
  }
}

// 获取问题列表
const fetchQuestionList = async () => {
  try {
    loading.value = true
    const params = {
      
      page: currentPage.value,
      limit: pageSize.value,
      keyword: globalStore.searchText,
      // keyword: keyword.value,
      type: activeTab.value,
      tagId: activeCategory.value || '',
      status: onlyUnsolved.value ? 'unsolved' : '',
      uid: curInfo.uid || ''
    }

    // 尝试调用API
    try {
      const res = await geQuestiontList(params)
      if (res.code === 0 && res.data) {
        questionList.value = res.data.list || []
        total.value = res.data.totalCount || 0
      } else {
        // API调用失败，使用mock数据
        throw new Error('API调用失败')
      }
    } catch (apiError) {
      console.log('API调用失败，使用mock数据：', apiError)
    }
  } catch (error) {
    console.error('获取问题列表失败：', error)
    // 确保有数据展示
    // questionList.value = mockQuestions.slice(0, pageSize.value)
    // total.value = mockQuestions.length
  } finally {
    loading.value = false
  }
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchQuestionList()
}

// 页面大小变化处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 切换页面大小时重置到第一页
  fetchQuestionList()
}
const emit = defineEmits(['getActiveTab'])

// 监听状态变化
watch(activeTab, () => {
  currentPage.value = 1 // 切换tab时重置页码
  emit('getActiveTab', activeTab)
  fetchQuestionList()
})

watch(keyword, () => {
  currentPage.value = 1
  fetchQuestionList()
})

// 监听全局搜索文本变化
watch(
  () => globalStore.searchText, // 使用函数形式确保能正确监听
  (newval,oldval) => {
    if(newval!=oldval) {
     activeTab.value = 'create_time'
     currentPage.value = 1
      fetchQuestionList()
    }
  },
  { flush: 'post' } // 添加flush选项确保DOM更新后执行
)


watch(sortType, () => {
  currentPage.value = 1
  fetchQuestionList()
})

watch(onlyUnsolved, () => {
  currentPage.value = 1
  fetchQuestionList()
})

watch(
  () => props.refreshData,
  (val) => {
     fetchQuestionList() // 提问成功后重新获取列表
  }
)

// 事件处理函数
// const handleQuestionSuccess = () => {
//   showQuestionDialog.value = false
//   fetchQuestionList() // 提问成功后重新获取列表
// }

// const openDialog = () => {
//   if (curInfo.question == 1) {
//     showQuestionDialog.value = true
//   } else {
//     ElMessage.error('您暂无提问权限，请联系管理员')
//   }
// }

const handleFilterChange = () => {
  currentPage.value = 1 // 重置页码
  fetchQuestionList()
}

const handleCategoryChange = (val) => {
  activeCategory.value = val
  currentPage.value = 1 // 重置页码
  fetchQuestionList()
}

// 组件挂载时获取数据
onMounted(async () => {
  const questionTab = sessionStorage.getItem('questionTab')
  if (questionTab) {
    activeTab.value = questionTab
  }
  await restorePageState() // 尝试恢复状态
  await loadCategories() // 获取分类数据
  await fetchQuestionList()
})

</script>

<style scoped>
.question-page-root {
  min-height: 100vh;
  /* background: #f6f8fa; */
  padding: 20px 0 32px 0;
}

.main-layout {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  gap: 40px;
  /* max-width: 1200px; */
  margin: 0 auto;
  min-height: 600px;
}

.main-left {
  flex: 1 1 0;
  min-width: 0;
  max-width: 1200px;

}

.main-right {
  width: 250px;
  min-width: 200px;
  display: flex;
  flex-direction: column;
  gap: 18px;
  align-self: flex-start;
  /* 卡片美化由子组件负责 */
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 32px;
  padding: 20px 0;
}

@media (max-width: 1024px) {
  .main-layout {
    flex-direction: column;
    gap: 0;
    max-width: 100vw;
    align-items: stretch;
  }

  .main-left {
    width: 100%;
    max-width: 100vw;
  }

  .main-right {
    width: 100%;
    min-width: 0;
    flex-direction: row;
    gap: 12px;
    margin-top: 18px;
    align-self: auto;
  }
}
</style>
